import { Directive } from 'vue'
import { ElMessage } from 'element-plus'

const numberDirective: Directive = {
  mounted(el, { value, arg }) {
    const min = value?.min
    const max = value?.max
    const positive = value?.positive
    const negative = value?.negative
    const decimal = value?.decimal
    const input = arg || el.querySelector('input')

    input.addEventListener('blur', () => {
      let value = Number(input.value)

      if (isNaN(value)) {
        ElMessage.warning('请输入数字')
        input.value = ''
      } else if (positive && value < 0) {
        ElMessage.warning('请输入正数')
        input.value = ''
      } else if (negative && value > 0) {
        ElMessage.warning('请输入负数')
        input.value = ''
      } else if (min !== undefined && value < min) {
        ElMessage.warning(`最小值为 ${min}`)
        input.value = ''
      } else if (max !== undefined && value > max) {
        ElMessage.warning(`最大值为 ${max}`)
        input.value = ''
      } else if (decimal !== undefined) {
        value = Number(value.toFixed(decimal))
        input.value = value.toString()
      }
    })
  },
}

export default numberDirective
